package com.xncoding.tomcat.socket02;

import com.xncoding.tomcat.socket01.HttpProtocolUtil;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

public class StaticResourceUtil {

    /**
     * 根据请求 url 获取完整绝对路径
     * @param url 请求 url
     * @return 完整绝对路径
     */
    public static String getAbsolutePath(String url) {
        String path = StaticResourceUtil.class.getResource("/").getPath();
        return path.replaceAll("\\\\", "/") + url;
    }

    /**
     * 输出静态资源信息
     *
     * @param inputStream  静态资源文件的读取流
     * @param outputStream 响应的输出流
     * @throws IOException
     */
    public static void outputStaticResource(InputStream inputStream, OutputStream outputStream) throws IOException {
        int count = 0;
        while (count == 0) {
            count = inputStream.available();
        }

        // 输出 http 请求头,然后再输出具体内容
        int resourceSize = count;
        // 读取内容输出
        outputStream.write(HttpProtocolUtil.getHttpHeader200(resourceSize).getBytes());
        // 已经读取的内容⻓度
        long written = 0;
        // 计划每次缓冲的⻓度
        int byteSize = 1024;
        byte[] bytes = new byte[byteSize];
        while (written < resourceSize) {
            // 说明剩余未读取⼤⼩不⾜⼀个 1024 ⻓度，那就按真实⻓度处理
            if (written + byteSize > resourceSize) {
                // 计算实际剩余内容
                byteSize = (int) (resourceSize - written);
                bytes = new byte[byteSize];
            }
            inputStream.read(bytes);
            outputStream.write(bytes);
            outputStream.flush();
            // 计算已经读取的长度
            written += byteSize;
        }
    }

}
